# -*- coding: utf-8 -*-

from __future__ import with_statement
import MySQLdb
from flask import Flask, g, request
import time
from hashlib import md5
from datetime import datetime
from contextlib import closing
from flask import session, url_for, redirect, render_template, abort, g, flash
from werkzeug import check_password_hash, generate_password_hash

app = Flask(__name__)
app.debug = True

import sae.core

@app.before_request
def before_request():
    appinfo = sae.core.Application()
    g.db = MySQLdb.connect(appinfo.mysql_host, appinfo.mysql_user, appinfo.mysql_pass,
    appinfo.mysql_db, port=int(appinfo.mysql_port))

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'): g.db.close()

@app.route('/')
def hello():
    return u"Hello, world!陈大请，承接软件开发！"
    
@app.route('/index', methods=['GET', 'POST'])    
def index():
    error = None
    if request.method == 'POST':
        user = query_db('''select * from user where  username = ?''', [request.form['username']], one=True)
        if user is None:
            error = u'无效用户名'
        elif not check_password_hash(user['pw_hash'], request.form['password']):
            error = u'无效密码'
        else:
            flash(u'你已经登录')
            session['user_id'] = user['user_id']
            #return redirect(url_for('timeline'))
    return render_template('index.html', error=error)

    

@app.route('/demo', methods=['GET', 'POST'])
def greeting():
    html = ''

    if request.method == 'POST':
        c = g.db.cursor()
        c.execute("insert into demo(text) values(%s)", (request.form['text']))

    html += """
    <form action="" method="post">
        <div><textarea cols="40" name="text"></textarea></div>
        <div><input type="submit" /></div>
    </form>
    """
    c = g.db.cursor()
    c.execute('select * from demo')
    msgs = list(c.fetchall())
    msgs.reverse()
    for row in msgs:
        html +=  '<p>' + row[-1] + '</p>'

    return html

